import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../data/models/destination_model.dart';

class DestinationService {
  // 动态确定API地址
  static String get baseUrl {
    if (kIsWeb) {
      return 'http://localhost:5000/api';
    }
    return 'http://localhost:5000/api';
  }

  final Dio _dio = Dio();

  DestinationService() {
    _dio.options.baseUrl = baseUrl;
    _dio.options.headers['Content-Type'] = 'application/json';
    _dio.options.connectTimeout = const Duration(seconds: 15);
    _dio.options.receiveTimeout = const Duration(seconds: 15);

    if (kIsWeb) {
      _dio.options.headers['Access-Control-Allow-Origin'] = '*';
      _dio.options.headers['Access-Control-Allow-Methods'] =
          'GET,PUT,POST,DELETE,OPTIONS';
      _dio.options.headers['Access-Control-Allow-Headers'] =
          'Content-Type,Authorization,X-Requested-With,Accept,Origin';
    }
  }

  // 获取目的地列表（分页）
  Future<DestinationPageResponse> getDestinations({
    int page = 1,
    int pageSize = 10,
    String sortBy = 'popular',
    String category = 'all',
    String? search,
  }) async {
    try {
      print(
        '🌍 获取目的地列表: page=$page, pageSize=$pageSize, sortBy=$sortBy, category=$category',
      );

      // 暂时使用模拟数据，后续可以替换为真实API
      await Future.delayed(const Duration(milliseconds: 500)); // 模拟网络延迟

      final mockData = _generateMockDestinations();

      // 应用搜索过滤
      List<Destination> filteredData = mockData;
      if (search != null && search.isNotEmpty) {
        filteredData =
            mockData
                .where(
                  (dest) =>
                      dest.name.toLowerCase().contains(search.toLowerCase()) ||
                      dest.location.toLowerCase().contains(
                        search.toLowerCase(),
                      ) ||
                      dest.description.toLowerCase().contains(
                        search.toLowerCase(),
                      ),
                )
                .toList();
      }

      // 应用类别过滤
      if (category != 'all') {
        filteredData =
            filteredData.where((dest) => dest.category == category).toList();
      }

      // 应用排序
      filteredData = _applySorting(filteredData, sortBy);

      // 应用分页
      final startIndex = (page - 1) * pageSize;
      final endIndex = startIndex + pageSize;

      final paginatedData =
          filteredData.length > startIndex
              ? filteredData.sublist(
                startIndex,
                endIndex > filteredData.length ? filteredData.length : endIndex,
              )
              : <Destination>[];

      final totalPages = (filteredData.length / pageSize).ceil();

      return DestinationPageResponse(
        destinations: paginatedData,
        currentPage: page,
        totalPages: totalPages,
        totalCount: filteredData.length,
        pageSize: pageSize,
      );
    } catch (e) {
      print('❌ 获取目的地列表失败: $e');
      rethrow;
    }
  }

  // 根据ID获取目的地详情
  Future<Destination?> getDestinationById(String id) async {
    try {
      print('🌍 获取目的地详情: $id');

      // 暂时使用模拟数据
      await Future.delayed(const Duration(milliseconds: 300));

      final mockData = _generateMockDestinations();
      return mockData.firstWhere(
        (dest) => dest.id == id,
        orElse: () => throw Exception('目的地不存在'),
      );
    } catch (e) {
      print('❌ 获取目的地详情失败: $e');
      rethrow;
    }
  }

  // 获取完整的目的地详情信息
  Future<DestinationDetail?> getDestinationDetail(String id) async {
    try {
      print('🌍 获取目的地完整详情: $id');

      // 模拟网络延迟
      await Future.delayed(const Duration(milliseconds: 800));

      // 返回模拟的详细数据
      final mockDetail = _generateMockDestinationDetail(id);
      return mockDetail;
    } catch (e) {
      print('❌ 获取目的地详情失败: $e');
      rethrow;
    }
  }

  // 应用排序逻辑
  List<Destination> _applySorting(
    List<Destination> destinations,
    String sortBy,
  ) {
    switch (sortBy) {
      case 'popular':
        destinations.sort((a, b) {
          if (a.isPopular && !b.isPopular) return -1;
          if (!a.isPopular && b.isPopular) return 1;
          return b.rating.compareTo(a.rating);
        });
        break;
      case 'name':
        destinations.sort((a, b) => a.name.compareTo(b.name));
        break;
      case 'rating':
        destinations.sort((a, b) => b.rating.compareTo(a.rating));
        break;
      case 'price':
        destinations.sort((a, b) => a.price.compareTo(b.price));
        break;
      case 'newest':
        destinations.sort((a, b) => b.createdAt.compareTo(a.createdAt));
        break;
    }
    return destinations;
  }

  // 生成模拟数据
  List<Destination> _generateMockDestinations() {
    return [
      Destination(
        id: '1',
        name: '圣托里尼岛',
        description: '希腊最美的海岛之一，以其蓝白相间的建筑和绝美夕阳而闻名世界。漫步在伊亚小镇，感受爱琴海的浪漫。',
        imageUrl:
            'https://images.unsplash.com/photo-1570077188670-e3a8d69ac5ff?w=800',
        category: 'beach',
        location: '希腊，爱琴海',
        rating: 4.8,
        reviewCount: 2847,
        price: 299.0,
        tags: ['海岛', '度假', '摄影', '浪漫'],
        isPopular: true,
        createdAt: DateTime.now().subtract(const Duration(days: 30)),
      ),
      Destination(
        id: '2',
        name: '雅典卫城',
        description: '古希腊文明的象征，巴特农神庙矗立在这里已有2500年。在这里，您可以触摸到古老文明的脉搏。',
        imageUrl:
            'https://images.unsplash.com/photo-1555993539-1732b0258189?w=800',
        category: 'culture',
        location: '希腊，雅典',
        rating: 4.6,
        reviewCount: 1523,
        price: 45.0,
        tags: ['历史', '文化', '古迹', '博物馆'],
        isPopular: true,
        createdAt: DateTime.now().subtract(const Duration(days: 15)),
      ),
      Destination(
        id: '3',
        name: '米克诺斯岛',
        description: '被称为"风车岛"的度假胜地，拥有迷人的白色建筑群和活跃的夜生活。这里是体验希腊岛屿文化的完美选择。',
        imageUrl:
            'https://images.unsplash.com/photo-1613395877344-13d4a8e0d49e?w=800',
        category: 'beach',
        location: '希腊，基克拉泽斯群岛',
        rating: 4.7,
        reviewCount: 967,
        price: 199.0,
        tags: ['海岛', '风车', '夜生活', '购物'],
        isPopular: false,
        createdAt: DateTime.now().subtract(const Duration(days: 45)),
      ),
      Destination(
        id: '4',
        name: '德尔菲',
        description: '古代世界的神谕中心，坐落在帕纳索斯山的山坡上。这里是阿波罗神庙的所在地，充满神秘色彩。',
        imageUrl:
            'https://images.unsplash.com/photo-1539650116574-75c0c6d75d3f?w=800',
        category: 'culture',
        location: '希腊，福基斯',
        rating: 4.4,
        reviewCount: 756,
        price: 35.0,
        tags: ['古迹', '神话', '山景', '考古'],
        isPopular: false,
        createdAt: DateTime.now().subtract(const Duration(days: 60)),
      ),
      Destination(
        id: '5',
        name: '克里特岛',
        description: '希腊最大的岛屿，拥有丰富的历史和壮丽的自然风光。从米诺安文明遗址到美丽的海滩，应有尽有。',
        imageUrl:
            'https://images.unsplash.com/photo-1548013146-72479768bada?w=800',
        category: 'nature',
        location: '希腊，克里特',
        rating: 4.5,
        reviewCount: 1334,
        price: 159.0,
        tags: ['海岛', '历史', '自然', '徒步'],
        isPopular: true,
        createdAt: DateTime.now().subtract(const Duration(days: 20)),
      ),
      Destination(
        id: '6',
        name: '萨洛尼卡',
        description: '希腊第二大城市，拥有丰富的拜占庭和奥斯曼文化遗产。这里有美味的美食和活跃的文化场景。',
        imageUrl:
            'https://images.unsplash.com/photo-1555209868-f9a1b7cd7e5f?w=800',
        category: 'city',
        location: '希腊，马其顿',
        rating: 4.3,
        reviewCount: 892,
        price: 89.0,
        tags: ['城市', '美食', '历史', '文化'],
        isPopular: false,
        createdAt: DateTime.now().subtract(const Duration(days: 10)),
      ),
      Destination(
        id: '7',
        name: '迈泰奥拉',
        description: '世界文化遗产，修道院悬挂在巨大的岩石柱上，景象壮观。这里是精神朝圣和摄影的绝佳地点。',
        imageUrl:
            'https://images.unsplash.com/photo-1539650116574-75c0c6d75d3f?w=800',
        category: 'nature',
        location: '希腊，色萨利',
        rating: 4.9,
        reviewCount: 2156,
        price: 25.0,
        tags: ['自然', '宗教', '摄影', '奇观'],
        isPopular: true,
        createdAt: DateTime.now().subtract(const Duration(days: 5)),
      ),
      Destination(
        id: '8',
        name: '罗德岛',
        description: '十字军时代的古城，被联合国教科文组织列为世界遗产。漫步在中世纪的街道上，感受历史的厚重。',
        imageUrl:
            'https://images.unsplash.com/photo-1601574968106-b312ac309953?w=800',
        category: 'culture',
        location: '希腊，多德卡尼斯群岛',
        rating: 4.4,
        reviewCount: 1687,
        price: 125.0,
        tags: ['历史', '古城', '海岛', '建筑'],
        isPopular: false,
        createdAt: DateTime.now().subtract(const Duration(days: 35)),
      ),
    ];
  }

  // 生成模拟的目的地详情数据
  DestinationDetail _generateMockDestinationDetail(String id) {
    switch (id) {
      case '1':
        return DestinationDetail(
          id: '1',
          name: '圣托里尼岛',
          nameEn: 'Santorini',
          description:
              '圣托里尼岛是希腊最著名的度假胜地之一，以其令人叹为观止的日落、独特的火山地貌和标志性的蓝白建筑而闻名于世。这个新月形的岛屿是约3600年前火山爆发形成的火山口，创造了世界上最壮观的景观之一。漫步在悬崖边的小径上，您会被无边的爱琴海美景所震撼，而伊亚村的日落更是被誉为世界上最美的日落之一。',
          shortDescription: '希腊最美海岛，以蓝白建筑和绝美日落闻名',
          country: '希腊',
          region: '基克拉泽斯群岛',
          address: 'Santorini, Cyclades, Greece',
          image:
              'https://images.unsplash.com/photo-1570077188670-e3a8d69ac5ff?w=800',
          imageGallery: [
            'https://images.unsplash.com/photo-1570077188670-e3a8d69ac5ff?w=800',
            'https://images.unsplash.com/photo-1613395877344-13d4a8e0d49e?w=800',
            'https://images.unsplash.com/photo-1571406252008-d6a2906a0def?w=800',
          ],
          coordinates: GeoCoordinates(lat: 36.3932, lng: 25.4615),
          rating: 4.8,
          reviewCount: 2847,
          popularLevel: 5,
          isPopular: true,
          category: 'beach',
          tags: ['海岛', '度假', '摄影', '浪漫', '日落'],
          priceRange: PriceRange(min: 150, max: 500, currency: 'EUR'),
          bestSeason: '4-6月，9-11月',
          visitDuration: '3-5天',
          transportation: TransportationInfo(
            airport: '圣托里尼机场(JTR)',
            publicTransport: '岛上巴士网络，出租车',
            driveTime: '建议租车或摩托车游览',
          ),
          language: '希腊语',
          timezone: 'UTC+2',
          climate: '地中海气候，夏季干燥炎热',
          currency: '欧元(EUR)',
          status: 'active',
          attractions: [
            AttractionInfo(
              id: 'attr1',
              name: '伊亚村',
              nameEn: 'Oia Village',
              description: '圣托里尼最著名的村庄，以其绝美的日落景色而闻名世界',
              image:
                  'https://images.unsplash.com/photo-1613395877344-13d4a8e0d49e?w=400',
              rating: 4.9,
              reviewCount: 1856,
              coordinates: GeoCoordinates(lat: 36.4618, lng: 25.3753),
            ),
            AttractionInfo(
              id: 'attr2',
              name: '费拉镇',
              nameEn: 'Fira Town',
              description: '圣托里尼的首府，拥有丰富的购物和餐饮选择',
              image:
                  'https://images.unsplash.com/photo-1571406252008-d6a2906a0def?w=400',
              rating: 4.6,
              reviewCount: 1247,
              coordinates: GeoCoordinates(lat: 36.4167, lng: 25.4309),
            ),
          ],
          hotels: [],
          nearbyDestinations: [
            DestinationSummary(
              id: '3',
              name: '米克诺斯岛',
              nameEn: 'Mykonos',
              image:
                  'https://images.unsplash.com/photo-1613395877344-13d4a8e0d49e?w=400',
              rating: 4.7,
              coordinates: GeoCoordinates(lat: 37.4467, lng: 25.3289),
              country: '希腊',
            ),
          ],
          createdAt: DateTime.now().subtract(const Duration(days: 30)),
          updatedAt: DateTime.now(),
        );

      case '3':
        return DestinationDetail(
          id: '3',
          name: '米克诺斯岛',
          nameEn: 'Mykonos',
          description:
              '米克诺斯岛被誉为"风车岛"，是希腊最受欢迎的度假胜地之一。这个迷人的岛屿以其传统的白色立方体建筑、狭窄的石板街道和著名的风车而闻名。米克诺斯拥有绝美的海滩、丰富的夜生活和高端的购物体验，是体验希腊岛屿文化的完美选择。',
          shortDescription: '希腊风车岛，拥有迷人白色建筑和活跃夜生活',
          country: '希腊',
          region: '基克拉泽斯群岛',
          address: 'Mykonos, Cyclades, Greece',
          image:
              'https://images.unsplash.com/photo-1613395877344-13d4a8e0d49e?w=800',
          imageGallery: [
            'https://images.unsplash.com/photo-1613395877344-13d4a8e0d49e?w=800',
            'https://images.unsplash.com/photo-1571406252008-d6a2906a0def?w=800',
          ],
          coordinates: GeoCoordinates(lat: 37.4467, lng: 25.3289),
          rating: 4.7,
          reviewCount: 967,
          popularLevel: 4,
          isPopular: false,
          category: 'beach',
          tags: ['海岛', '风车', '夜生活', '购物', '海滩'],
          priceRange: PriceRange(min: 100, max: 400, currency: 'EUR'),
          bestSeason: '5-9月',
          visitDuration: '2-4天',
          transportation: TransportationInfo(
            airport: '米克诺斯机场(JMK)',
            publicTransport: '岛上巴士，出租车',
            driveTime: '建议租车或ATV游览',
          ),
          language: '希腊语',
          timezone: 'UTC+2',
          climate: '地中海气候',
          currency: '欧元(EUR)',
          status: 'active',
          attractions: [
            AttractionInfo(
              id: 'attr4',
              name: '米克诺斯风车',
              nameEn: 'Mykonos Windmills',
              description: '岛上最著名的地标，16世纪建造的传统风车',
              image:
                  'https://images.unsplash.com/photo-1613395877344-13d4a8e0d49e?w=400',
              rating: 4.6,
              reviewCount: 856,
              coordinates: GeoCoordinates(lat: 37.4467, lng: 25.3289),
            ),
          ],
          hotels: [],
          nearbyDestinations: [
            DestinationSummary(
              id: '1',
              name: '圣托里尼岛',
              nameEn: 'Santorini',
              image:
                  'https://images.unsplash.com/photo-1570077188670-e3a8d69ac5ff?w=400',
              rating: 4.8,
              coordinates: GeoCoordinates(lat: 36.3932, lng: 25.4615),
              country: '希腊',
            ),
          ],
          createdAt: DateTime.now().subtract(const Duration(days: 45)),
          updatedAt: DateTime.now(),
        );

      case '4':
        return DestinationDetail(
          id: '4',
          name: '德尔菲',
          nameEn: 'Delphi',
          description:
              '德尔菲是古代世界最重要的宗教中心之一，被认为是世界的中心。这里是著名的德尔菲神谕的所在地，阿波罗神庙的遗址至今仍能让人感受到古代的神秘氛围。坐落在帕纳索斯山的山坡上，德尔菲不仅有着深厚的历史文化底蕴，还拥有壮丽的山景。',
          shortDescription: '古代神谕中心，阿波罗神庙遗址',
          country: '希腊',
          region: '福基斯',
          address: 'Delphi, Phocis, Greece',
          image:
              'https://images.unsplash.com/photo-1539650116574-75c0c6d75d3f?w=800',
          imageGallery: [
            'https://images.unsplash.com/photo-1539650116574-75c0c6d75d3f?w=800',
          ],
          coordinates: GeoCoordinates(lat: 38.4824, lng: 22.5009),
          rating: 4.4,
          reviewCount: 756,
          popularLevel: 3,
          isPopular: false,
          category: 'culture',
          tags: ['古迹', '神话', '山景', '考古', '历史'],
          priceRange: PriceRange(min: 15, max: 35, currency: 'EUR'),
          bestSeason: '4-6月，9-11月',
          visitDuration: '半天',
          transportation: TransportationInfo(
            airport: '最近机场：雅典国际机场(ATH)',
            publicTransport: '从雅典乘坐巴士约2.5小时',
            driveTime: '从雅典开车约2小时',
          ),
          language: '希腊语',
          timezone: 'UTC+2',
          climate: '地中海山地气候',
          currency: '欧元(EUR)',
          status: 'active',
          attractions: [
            AttractionInfo(
              id: 'attr5',
              name: '阿波罗神庙',
              nameEn: 'Temple of Apollo',
              description: '古代德尔菲神谕的中心，阿波罗神的圣地',
              image:
                  'https://images.unsplash.com/photo-1539650116574-75c0c6d75d3f?w=400',
              rating: 4.7,
              reviewCount: 634,
              coordinates: GeoCoordinates(lat: 38.4824, lng: 22.5009),
            ),
          ],
          hotels: [],
          nearbyDestinations: [
            DestinationSummary(
              id: '2',
              name: '雅典卫城',
              nameEn: 'Acropolis of Athens',
              image:
                  'https://images.unsplash.com/photo-1555993539-1732b0258189?w=400',
              rating: 4.6,
              coordinates: GeoCoordinates(lat: 37.9715, lng: 23.7267),
              country: '希腊',
            ),
          ],
          createdAt: DateTime.now().subtract(const Duration(days: 60)),
          updatedAt: DateTime.now(),
        );

      case '5':
        return DestinationDetail(
          id: '5',
          name: '克里特岛',
          nameEn: 'Crete',
          description:
              '克里特岛是希腊最大的岛屿，拥有丰富的历史和壮丽的自然风光。这里是古代米诺安文明的发源地，拥有克诺索斯宫等重要考古遗址。从美丽的海滩到雄伟的山脉，从古老的修道院到现代的度假村，克里特岛为每位游客提供了独特的体验。',
          shortDescription: '希腊最大岛屿，米诺安文明发源地',
          country: '希腊',
          region: '克里特',
          address: 'Crete, Greece',
          image:
              'https://images.unsplash.com/photo-1548013146-72479768bada?w=800',
          imageGallery: [
            'https://images.unsplash.com/photo-1548013146-72479768bada?w=800',
          ],
          coordinates: GeoCoordinates(lat: 35.2401, lng: 24.8093),
          rating: 4.5,
          reviewCount: 1334,
          popularLevel: 4,
          isPopular: true,
          category: 'nature',
          tags: ['海岛', '历史', '自然', '徒步', '海滩'],
          priceRange: PriceRange(min: 80, max: 300, currency: 'EUR'),
          bestSeason: '4-6月，9-11月',
          visitDuration: '5-7天',
          transportation: TransportationInfo(
            airport: '伊拉克利翁机场(HER)，哈尼亚机场(CHQ)',
            publicTransport: '岛上巴士网络发达',
            driveTime: '建议租车游览全岛',
          ),
          language: '希腊语',
          timezone: 'UTC+2',
          climate: '地中海气候',
          currency: '欧元(EUR)',
          status: 'active',
          attractions: [
            AttractionInfo(
              id: 'attr6',
              name: '克诺索斯宫',
              nameEn: 'Palace of Knossos',
              description: '欧洲最古老的城市，米诺安文明的中心',
              image:
                  'https://images.unsplash.com/photo-1548013146-72479768bada?w=400',
              rating: 4.3,
              reviewCount: 987,
              coordinates: GeoCoordinates(lat: 35.2978, lng: 25.1630),
            ),
          ],
          hotels: [],
          nearbyDestinations: [
            DestinationSummary(
              id: '1',
              name: '圣托里尼岛',
              nameEn: 'Santorini',
              image:
                  'https://images.unsplash.com/photo-1570077188670-e3a8d69ac5ff?w=400',
              rating: 4.8,
              coordinates: GeoCoordinates(lat: 36.3932, lng: 25.4615),
              country: '希腊',
            ),
          ],
          createdAt: DateTime.now().subtract(const Duration(days: 20)),
          updatedAt: DateTime.now(),
        );

      case '2':
        return DestinationDetail(
          id: '2',
          name: '雅典卫城',
          nameEn: 'Acropolis of Athens',
          description:
              '雅典卫城是古希腊文明的象征，也是世界上最著名的古代建筑群之一。巴特农神庙矗立在这里已有2500年，见证了古希腊的辉煌。登上卫城山，您不仅可以欣赏到精美的古典建筑，还能俯瞰整个雅典城。这里是了解古希腊历史文化的最佳场所。',
          shortDescription: '古希腊文明象征，巴特农神庙所在地',
          country: '希腊',
          region: '阿提卡',
          address: 'Athens, Attica, Greece',
          image:
              'https://images.unsplash.com/photo-1555993539-1732b0258189?w=800',
          imageGallery: [
            'https://images.unsplash.com/photo-1555993539-1732b0258189?w=800',
            'https://images.unsplash.com/photo-1581833971358-2c8b550f87b3?w=800',
          ],
          coordinates: GeoCoordinates(lat: 37.9715, lng: 23.7267),
          rating: 4.6,
          reviewCount: 1523,
          popularLevel: 5,
          isPopular: true,
          category: 'culture',
          tags: ['古迹', '历史', '文化', '世界遗产', '必游'],
          priceRange: PriceRange(min: 20, max: 30, currency: 'EUR'),
          bestSeason: '4-6月，9-11月',
          visitDuration: '半天',
          transportation: TransportationInfo(
            airport: '雅典国际机场(ATH)',
            publicTransport: '地铁红线至Akropoli站',
            driveTime: '从市中心约15分钟',
          ),
          language: '希腊语',
          timezone: 'UTC+2',
          climate: '地中海气候',
          currency: '欧元(EUR)',
          status: 'active',
          attractions: [
            AttractionInfo(
              id: 'attr3',
              name: '帕特农神庙',
              nameEn: 'Parthenon',
              description: '献给雅典娜女神的古希腊神庙，古典建筑的典范',
              image:
                  'https://images.unsplash.com/photo-1581833971358-2c8b550f87b3?w=400',
              rating: 4.9,
              reviewCount: 1520,
              coordinates: GeoCoordinates(lat: 37.9715, lng: 23.7267),
            ),
          ],
          hotels: [],
          nearbyDestinations: [
            DestinationSummary(
              id: '4',
              name: '德尔菲',
              nameEn: 'Delphi',
              image:
                  'https://images.unsplash.com/photo-1539650116574-75c0c6d75d3f?w=400',
              rating: 4.4,
              coordinates: GeoCoordinates(lat: 38.4824, lng: 22.5009),
              country: '希腊',
            ),
          ],
          createdAt: DateTime.now().subtract(const Duration(days: 15)),
          updatedAt: DateTime.now(),
        );

      default:
        throw Exception('目的地不存在');
    }
  }
}
